package room_event

import (
	"encoding/json"
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/chat"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/messages/private_chat"
	pvt_chat2 "longmen/server/internal/rpc/tencentim/pvt_chat"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/pkg/common/report"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"time"

	"github.com/spf13/cast"
)

// 私聊消息发送
func handlingPrivateMessage(user *chat.ClientUser, fromAccount string, data []byte) (*pb.CallbackResp, error) {
	// 是否被禁
	if db_main.CheckBan(user.UserId) > 0 {
		return utils.C2CRejectMessage("已被禁止私聊"), nil
	}
	// 统计发起人数
	db_live.LiveSendChatNum(user.RoomId, user.UserId)

	user.UserId = cast.ToInt(fromAccount)
	global2.Log.Debugf("私聊内容:%s,fromAccount:%s,平台::%s", string(data), fromAccount, user.OptPlatform)
	// 判断是否发言频繁
	if !global2.GetRds().SetNX(fmt.Sprintf("user_say:%d", user.UserId), 1, time.Second*1).Val() {
		return utils.C2CRejectMessage("发言频繁"), nil
	}

	// 主播已设置：未回复仅接收30条信息
	num := cache.GetPrivateChatUnread(user.UserId, user.RoomId)
	if num >= 1000 {
		return utils.C2CRejectMessage("发言频繁，等待主播回复"), nil
	}

	// 判断是否被禁言
	b, _ := cache.GetPrivateChatBan(user.UserId, user.RoomId)
	if b {
		return utils.C2CRejectMessage("用户被禁言"), nil
	}

	say := private_chat.SayMessage{}
	err := json.Unmarshal(data, &say)
	if err != nil {
		return utils.C2CRejectMessage("发言内容错误"), nil
	}

	var content string
	content, err = cache.AesDescrypt(say.Content)
	if err != nil {
		global2.Log.Error(err)
		return utils.C2CRejectMessage("发言内容错误"), nil
	}
	say.Content = content
	var conversationId string
	//查询正在进行的会话, 无则创建新会话
	if u, err := cache.GetUserFullInfo(user.RoomId); err == nil && u.Id > 0 {
		if user.Avatar == "" {
			user.Avatar = cache.GetConfigPub().DefaultAvatarUrl
		}
		if say.ImgUrl != "" && say.Content == "" {
			content = "图片/视频消息..."
		}
		session, err := pvt_chat2.SetSingleChatConversationUserReplyFlag(cast.ToString(user.UserId), cast.ToString(user.RoomId), content, user.IP, user.OptPlatform, say.Channel)
		if err != nil {
			global2.Log.Error(err)
			return utils.C2CRejectMessage("会话已结束或不存在"), nil
		}
		conversationId = session.ConversationId
	}

	if conversationId == "" {
		return utils.CallbackOkResp(""), nil
	}

	sender := pvt_chat2.UserSender
	if user.Anonymouse {
		sender = pvt_chat2.AnonymousSender
	}
	historyMsg := pvt_chat2.History{
		SessionId:  conversationId,
		SenderUid:  cast.ToString(user.UserId),
		SenderTag:  sender,
		ReceiveUid: cast.ToString(say.GroupId),
		Content:    say.Content,
		SendTime:   time.Now().UnixMilli(),
		ImgUrl:     say.ImgUrl,
	}

	// 聊天历史写入到ES
	_, writeOk := historyMsg.WriteToEs()
	if !writeOk {
		return utils.C2CRejectMessage("发送频繁，请休息一下"), nil
	}
	err = cache.IncrPrivateChatUnreadNum(user.UserId, say.GroupId)
	if err == nil {
		cache.SetAnchorUnreadNum(say.GroupId, conversationId)
	}

	found := false
	for _, v := range db_main.DefaultChatAdmin() {
		if v.AnchorId == cast.ToString(user.RoomId) {
			found = true
			break
		}
	}
	if !found { //不是给默认主播回复则加1
		err = report.NewImReport().IncrBatchReplyNum(cast.ToString(user.UserId))
		if err != nil {
			global2.Log.Errorf("ImReport IncrBatchReplyNum :%v", err)
		}
		err = report.NewImReport().IncrBatchReadNum(cast.ToString(user.UserId))
		if err != nil {
			global2.Log.Errorf("ImReport IncrBatchReadNum err:%v", err)
		}
		//cache3.RoomUserOnline(user.RoomId, user.UserId)
	}
	err = global2.PublishPvtChat.BroadCast(historyMsg)
	if err != nil {
		global2.Log.Errorf("publish private message error: %v", err)
		return utils.C2CRejectMessage("发送失败，请重试"), nil
	}
	//私聊统计
	userPrivateChatLog := &models_main.UserPrivateChatLog{}
	userPrivateChatLog.SenderUid = user.UserId
	userPrivateChatLog.ReceiveUid = user.RoomId
	userPrivateChatLog.SourceKey = user.SourceKey
	go db_main.InsertStatPrivateChat(userPrivateChatLog)
	// 允许发言
	return utils.CallbackOkResp(""), nil
}

// 私聊历史消息
func handlingPrivateHistory(user *chat.ClientUser, data []byte) (*pb.CallbackResp, error) {
	his := private_chat.HistoryMessage{}
	err := json.Unmarshal(data, &his)
	if err != nil {
		return nil, err
	}
	history, total := pvt_chat2.GetHistory([]string{cast.ToString(his.GroupId)}, his.Page, his.Limit)
	resp := private_chat.HistoryResponse{
		SentMessageStruct: messages2.SentMessageStruct{Type: messages2.PrivateHistoryReplyType},
		Data:              history,
		Total:             total,
	}
	return utils.CallbackOkAndExt(resp, ""), nil
}
